package communication;

import java.io.IOException;

import org.ftp4che.io.BandwidthControlledInputStream;
import org.ftp4che.io.BandwidthControlledOutputStream;

public class ClientSecureConnectionControlled extends ClientSecureConnection {
	

	private static final int KBits = 128;

	protected BandwidthControlledOutputStream sendControlled;
	protected BandwidthControlledInputStream receiveControlled;
	
	
	public ClientSecureConnectionControlled(String hostname, int port, int bandwidth)
            throws ConnectionException{
		super(hostname,port);
		
		sendControlled = new BandwidthControlledOutputStream(send,bandwidth*KBits);
		receiveControlled = new BandwidthControlledInputStream(receive,bandwidth*KBits);
	}

	
	protected void doSend(byte[] buffer)
            throws ConnectionException {
		try {
			sendControlled.write(buffer);
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}
	}


	protected void doSend(byte[] buffer, int init, int length)
            throws ConnectionException {
		try {
			sendControlled.write(buffer,init,length);
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}		
	}

    protected int doReceiveBytes(byte [] buffer)
            throws ConnectionException {
		try {
			return receiveControlled.read(buffer);
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}
	}

	
	protected void doClose()
            throws ConnectionException{
		try {
			if(socket!=null){
				socket.close();	
				socket = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}

		try {
			if(send!=null){
				send.close();
				send = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}

		try {
			if(receive!=null){
				receive.close();
				receive = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}

		try {
			if(sendControlled!=null){
				sendControlled.close();	
				sendControlled = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}

		try {
			if(receiveControlled!=null){
				receiveControlled.close();
				receiveControlled = null;
			}
		} catch (IOException e) {
			throw new ConnectionException(e.getMessage());
		}		
	}


}
